﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ActionSystem.Core;
using XMLib;

namespace ActionSystem.Camera
{
    /// <summary>
    /// 横板3D视角,有z轴移动
    /// </summary>
    [ActionConfig(typeof(Fixed3DDirectionActionHandler))]
    public class Fixed3DDirectionActionConfig : BaseStateActionConfig
    {
        [CustomLabel("距离跟随的距离")]
        public float distance = 20;
        [CustomLabel("Y偏移")]
        public float offsetUp = 0.8f;
        [CustomLabel("相机右方")]
        public Vector3 right = Vector3.right;
        [CustomLabel("相机前方")]
        public Vector3 forward = Vector3.forward;
        [CustomLabel("跟踪速度")]
        public float speed = 1;
    }
    public class Fixed3DDirectionActionHandler : BaseCameraHander
    {
        Fixed3DDirectionActionConfig config;
        Quaternion targetRotation;
        float baseSpeed = 0;
        public override void Enter(BaseStateAction action)
        {
            base.Enter(action);
            config = action.Config as Fixed3DDirectionActionConfig;
            baseSpeed = config.speed / (1 + config.speed);//speed越大，速度越快
            targetRotation = Quaternion.LookRotation(config.forward, Vector3.Cross(config.forward, config.right));
        }
        public override void Update(BaseStateAction action, float deltaTime)
        {
            //更新相机位置和朝向
            if (follow == null || config == null)
            {
                return;
            }
            var targetposition = follow.GetFallowPostion() + config.offsetUp * follow.GetFallowUpDirection() + (-config.distance * config.forward);
            //更新相机位置
            float t = (camera.transform.position - targetposition).magnitude;
            t = baseSpeed + (1 - baseSpeed) * t / (1 + t);
            camera.transform.position = Vector3.Lerp(camera.transform.position, targetposition, t);
            //朝向
            camera.transform.rotation = Quaternion.Slerp(camera.transform.rotation, targetRotation, t);            
        }

        public override void PostUpdate(BaseStateAction action, float deltaTime)
        {
            //更新ICameraInfo
            if (cameraMachine != null && cameraMachine.GetCamera() != null)
            {
                info?.SetMoveFarwrd(Vector3.Cross(cameraMachine.GetCamera().transform.right,follow.GetFallowUpDirection()));
                info?.SetMoveRight(cameraMachine.GetCamera().transform.right);
                info?.SetMoveUp(follow.GetFallowUpDirection());
            }
            else
            {
                info?.SetMoveFarwrd(Vector3.zero);
                info?.SetMoveRight(Vector3.zero);
                info?.SetMoveUp(Vector3.zero);
            }
        }
    }
}